<template>
  <div class="edit-writer">
    <div class="edit-writer-container form-common">
      <h1 class="title-common">{{ isEdit ? '修改作家信息' : '新增作家' }}</h1>
      
      <div class="form-container">
        <form @submit.prevent="handleSubmit" class="edit-form">
          <div class="form-group">
            <label for="name">作家名称</label>
            <input 
              type="text" 
              id="name" 
              v-model="form.name" 
              required
              placeholder="请输入作家名称"
              class="form-control"
            >
          </div>

          <div class="form-group">
            <label for="experience">生平简介</label>
            <textarea 
              id="experience" 
              v-model="form.experience" 
              required
              placeholder="请输入作家生平简介"
              rows="10"
              class="form-control"
            ></textarea>
          </div>

          <FileUpload
            label="头像"
            input-id="avatar"
            :value="form.avatar"
            :preview-url="avatarPreview"
            @change="handleAvatarChange"
          />

          <div class="form-actions">
            <button type="submit" class="submit-btn">
              {{ isEdit ? '保存修改' : '添加作家' }}
            </button>
            <button type="button" class="cancel-btn" @click="goBack">取消</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 使用通用成功弹窗组件 -->
    <FormModal
      :show="showSuccess"
      title="添加成功"
      message="添加成功。"
      :countdown-seconds="countdownSeconds"
      @close="goToSourcePage"
      @confirm="goToSourcePage"
    />
  </div>
</template>

<script>
import FormModal from '@/components/FormModal.vue'
import FileUpload from '@/components/FileUpload.vue'

export default {
  name: 'EditWriter',
  components: {
    FormModal,
    FileUpload
  },
  data() {
    return {
      form: {
        name: '',
        experience: '',
        avatar: null
      },
      avatarPreview: null,
      isEdit: false,
      showSuccess: false,
      countdownSeconds: 5,
      countdownTimer: null,
      sourcePage: null
    }
  },
  methods: {
    handleAvatarChange(file) {
      this.form.avatar = file
      if (file) {
        this.avatarPreview = URL.createObjectURL(file)
      }
    },
    async handleSubmit() {
      try {
        const formData = new FormData()
        formData.append('name', this.form.name)
        formData.append('experience', this.form.experience)
        if (this.form.avatar) {
          formData.append('avatar', this.form.avatar)
        }

        if (this.isEdit) {
          await this.$axios.put(`/api/writers/${this.$route.params.id}`, formData)
        } else {
          await this.$axios.post('/api/writers', formData)
        }

        // 显示成功弹窗
        this.showSuccess = true
        this.countdownSeconds = 5
        this.countdownTimer = setInterval(() => {
          this.countdownSeconds--
          if (this.countdownSeconds <= 0) {
            this.goToSourcePage()
          }
        }, 1000)
      } catch (error) {
        alert('保存失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    goBack() {
      this.$router.back()
    },
    goToSourcePage() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
        this.countdownTimer = null
      }
      
      if (this.sourcePage) {
        this.$router.push(this.sourcePage)
      } else {
        this.$router.push('/user')
      }
    },
    async fetchWriter() {
      try {
        const response = await this.$axios.get(`/api/writers/${this.$route.params.id}`)
        const writer = response.data
        this.form.name = writer.name
        this.form.experience = writer.experience
        if (writer.avatar_path) {
          // 如果是相对路径，添加服务器地址
          if (writer.avatar_path.startsWith('/')) {
            this.avatarPreview = `http://localhost:3000${writer.avatar_path}`
          } else {
          this.avatarPreview = writer.avatar_path
          }
        }
      } catch (error) {
        console.error('获取作家信息失败：', error)
      }
    }
  },
  created() {
    // 记录来源页面
    if (this.$route.query.from) {
      this.sourcePage = this.$route.query.from
    } else if (this.$route.params.id) {
      this.sourcePage = `/experience/${this.$route.params.id}`
    } else {
      this.sourcePage = '/user'
    }
    
    if (this.$route.params.id) {
      this.isEdit = true
      this.fetchWriter()
    }
  },
  beforeDestroy() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
    }
  }
}
</script>

<style scoped>
@import '../assets/css/common.css';

.edit-writer {
  padding: 2rem;
  background-color: #f4f7f6;
  min-height: 100vh;
}

.edit-writer .title-common {
  margin-bottom: 3rem;
}

.edit-writer .title-common h1 {
  text-align: center;
  padding-bottom: 10px;
  border-bottom: #3F6580 solid 1px;
  color: #2c3e50;
  font-size: 24px;
  margin: 0 !important;
  padding-bottom: 10px !important;
}

.edit-writer .form-container {
  margin-top: 3rem;
}
</style> 